"""维普检测平台实现"""

from typing import Optional, Dict, Any

from app.models.enums import DetectionStatus, DetectionPlatform
from app.models.response import TextDetectionResponse
from app.utils.exceptions import PlatformAPIException
from .base import BaseDetectionPlatform


class WeipuDetectionPlatform(BaseDetectionPlatform):
    """维普检测平台"""
    
    def __init__(self, api_url: str, api_key: str):
        super().__init__(api_url, api_key, DetectionPlatform.WEIPU)
    
    async def submit_detection(self, text: str, title: Optional[str] = None, 
                             author: Optional[str] = None) -> TextDetectionResponse:
        """提交维普检测任务"""
        try:
            self.logger.info("提交维普检测任务")
            
            # 验证文本
            if not self._validate_text_for_platform(text):
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "文本不符合维普检测要求"
                )
            
            # 准备请求数据
            data = {
                "text": text,
                "title": title or "未命名文档",
                "author": author or "匿名",
                "detect_mode": "standard",  # 维普标准检测
                "compare_lib": "all",  # 对比库：全部
                "exclude_self": True,  # 排除自引
                "exclude_ref": True   # 排除参考文献
            }
            
            # 发送API请求
            response = await self._make_api_request("POST", "/api/detect", data)
            
            # 处理响应
            task_id = response.get("detect_id") or response.get("task_id")
            if not task_id:
                raise PlatformAPIException(
                    self.platform_name.value, 
                    "未获取到任务ID"
                )
            
            return self._create_response(
                task_id=task_id,
                status=DetectionStatus.PENDING
            )
            
        except PlatformAPIException:
            raise
        except Exception as e:
            self.logger.error(f"维普检测任务提交失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"任务提交失败: {str(e)}"
            )
    
    async def get_detection_result(self, task_id: str) -> TextDetectionResponse:
        """获取维普检测结果"""
        try:
            self.logger.info(f"获取维普检测结果: {task_id}")
            
            # 发送查询请求
            response = await self._make_api_request("GET", f"/api/result/{task_id}")
            
            # 解析响应
            status_map = {
                "submit": DetectionStatus.PENDING,
                "detect": DetectionStatus.PROCESSING,
                "success": DetectionStatus.COMPLETED,
                "fail": DetectionStatus.FAILED
            }
            
            status = status_map.get(
                response.get("status", "submit"), 
                DetectionStatus.PENDING
            )
            
            similarity_rate = response.get("similarity_ratio")
            if similarity_rate is not None:
                similarity_rate = float(similarity_rate) / 100  # 转换为小数
            
            report_url = response.get("report_url") or response.get("html_url")
            
            return self._create_response(
                task_id=task_id,
                status=status,
                similarity_rate=similarity_rate,
                report_url=report_url
            )
            
        except Exception as e:
            self.logger.error(f"获取维普检测结果失败: {e}")
            raise PlatformAPIException(
                self.platform_name.value, 
                f"获取结果失败: {str(e)}"
            )
    
    async def cancel_detection(self, task_id: str) -> bool:
        """取消维普检测任务"""
        try:
            self.logger.info(f"取消维普检测任务: {task_id}")
            
            response = await self._make_api_request("POST", f"/api/cancel", {"detect_id": task_id})
            
            return response.get("success", False)
            
        except Exception as e:
            self.logger.error(f"取消维普检测任务失败: {e}")
            return False
    
    def _platform_specific_validation(self, text: str) -> bool:
        """维普平台特定验证"""
        # 维普要求最少200字
        if len(text.strip()) < 200:
            return False
        
        # 维普单次检测最大50万字
        if len(text.strip()) > 500000:
            return False
        
        return True
    
    def _get_platform_features(self) -> list[str]:
        """获取维普平台特性"""
        return [
            "学术论文检测",
            "期刊论文检测",
            "学位论文检测",
            "科技报告检测",
            "专利文献检测",
            "标准规范检测",
            "互联网资源检测",
            "图书资源检测",
            "多级相似度分析",
            "智能排版识别"
        ]
    
    async def get_compare_libraries(self) -> list[Dict[str, Any]]:
        """获取对比库列表（维普特有功能）"""
        try:
            self.logger.info("获取维普对比库列表")
            
            response = await self._make_api_request("GET", "/api/libraries")
            
            return response.get("libraries", [])
            
        except Exception as e:
            self.logger.error(f"获取对比库列表失败: {e}")
            return []
    
    async def get_detection_report_formats(self, task_id: str) -> Dict[str, str]:
        """获取检测报告的多种格式（维普特有功能）"""
        try:
            self.logger.info(f"获取检测报告格式: {task_id}")
            
            response = await self._make_api_request("GET", f"/api/report/formats/{task_id}")
            
            return {
                "html_url": response.get("html_url"),
                "pdf_url": response.get("pdf_url"),
                "word_url": response.get("word_url"),
                "simple_url": response.get("simple_url")
            }
            
        except Exception as e:
            self.logger.error(f"获取报告格式失败: {e}")
            return {}
    
    async def set_detection_options(self, task_id: str, options: Dict[str, Any]) -> bool:
        """设置检测选项（维普特有功能）"""
        try:
            self.logger.info(f"设置检测选项: {task_id}")
            
            data = {
                "detect_id": task_id,
                "options": options
            }
            
            response = await self._make_api_request("POST", "/api/options", data)
            
            return response.get("success", False)
            
        except Exception as e:
            self.logger.error(f"设置检测选项失败: {e}")
            return False 